#include<bits/stdc++.h>
using namespace std;
inline int read(){
	int x=0;bool f=0;char ch=getchar();
	while(ch<'0'||ch>'9')f^=(ch=='-'),ch=getchar();
	while('0'<=ch&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
	return f?-x:x;
}
const int Maxn=1005;
int T;
int n,mod;
int a[1005][1005],b[1005][1005],c[1005][1005];
int sum[1005][1005];
int main(){
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	T=read();
	while(T--){
		mod=read();n=read();
		for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)a[i][j]=read();
		for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)b[j][i]=read();
		for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)c[i][j]=read();
		int ok=0;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				int res=0;
				for(int k=1;k<=n;k++)res=(res+1ll*a[i][k]*b[j][k]%mod)%mod;
				if(res!=c[i][j]){puts("No");ok=1;break;}
			}
			if(ok)break;
		}
		if(!ok)puts("Yes");
	}
	return 0;
}

